package httpHandle

import (
	"github.com/gin-gonic/gin"
	"github.com/wzh200x/webServer/constants"
	"github.com/wzh200x/webServer/httpHandle/service"
	"github.com/wzh200x/webServer/middleware/auth"
	"github.com/wzh200x/webServer/middleware/response"
)

// 登录请求结构
type LoginRequest service.AuthRequest

// 登录响应结构
type LoginResponse service.AuthResponse

// HandleLogin 处理用户登录
func HandleLogin(c *gin.Context) {
	success, err := response.GetResponseFuncs(c)

	var loginReq service.AuthRequest
	if bindErr := c.ShouldBind(&loginReq); bindErr != nil {
		err(constants.ErrAuth, "无效的请求参数")
		return
	}

	// 调用认证服务进行用户验证
	authResponse, authErr := service.AuthenticateUser(loginReq)
	if authErr != nil {
		err(constants.ErrAuth, "认证失败: "+authErr.Error())
		return
	}

	// 密码错误
	if authResponse == nil {
		err(constants.ErrAuth, "用户名或密码错误")
		return
	}

	// 返回认证结果
	success(authResponse)
}

// HandleProtected 受保护的接口示例
func HandleProtected(c *gin.Context) {
	success, _ := response.GetResponseFuncs(c)

	// 从上下文中获取用户信息
	userID, username := auth.GetCurrentUser(c)

	success(gin.H{
		"message":  "这是受保护的接口",
		"user_id":  userID,
		"username": username,
	})
}

// RefreshTokenRequest 刷新令牌请求结构
type RefreshTokenRequest struct {
	Token string `json:"token" form:"token" binding:"required"`
}

// RefreshTokenResponse 刷新令牌响应结构
type RefreshTokenResponse struct {
	Token           string `json:"token"`
	TokenExpireTime int64  `json:"tokenExpireTime"` // 令牌过期时间戳
}

// HandleRefreshToken 处理令牌刷新
func HandleRefreshToken(c *gin.Context) {
	success, err := response.GetResponseFuncs(c)

	var refreshReq RefreshTokenRequest
	if bindErr := c.ShouldBind(&refreshReq); bindErr != nil {
		err(constants.ErrAuth, "无效的请求参数")
		return
	}

	// 调用令牌刷新服务
	newToken, expireTime, refreshErr := service.RefreshToken(refreshReq.Token)
	if refreshErr != nil {
		err(constants.ErrAuthToken, "刷新令牌失败: "+refreshErr.Error())
		return
	}

	// 返回新令牌
	success(RefreshTokenResponse{
		Token:           newToken,
		TokenExpireTime: expireTime,
	})
}
